<template>
  <Dialog title="设置库存" v-model="dialogVisible" width="1000px">
    <view class="shop-selector">
      <el-select v-model="selectedShopId" class="w-80!" placeholder="请选择店铺">
        <el-option
          v-for="item in shopList"
          :key="item.id"
          :label="item.name"
          :value="item.id as number"
        />
      </el-select>
      <el-button @click="setStock" type="primary" :disabled="formLoading">设置库存</el-button>
      <el-button @click="batchSetStock" type="primary" :disabled="formLoading">批量设置库存</el-button>
    </view>

    <el-table :data="skuRef.shopStockList" border class="tabNumWidth" style="margin-top: 20px;"  max-height="500" size="small">
      <el-table-column align="center" label="店铺" min-width="168">
        <template #default="{ row }">
          {{ row.shopName }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="类型" min-width="168">
        <template #default="scope">
          {{ scope.row.shopType === 0 ? '总店' : '分店' }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="进货价" min-width="168">
        <template #default="{ row }">
          <el-input-number
            v-model="row.supplyPrice"
            :min="0"
            :precision="2"
            :step="0.01"
            class="w-100%"
            controls-position="right"
          />
        </template>
      </el-table-column>

      <el-table-column align="center" label="库存" min-width="168">
        <template #default="{ row }">
          <el-input-number v-model="row.stock" :min="0" class="w-100%" controls-position="right" />
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" min-width="108">
        <template #default="scope">
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.shopId)"
            v-hasPermi="['shop:shop:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ProductInventoryApi, ProductInventoryVO } from '@/api/mall/product/shopStock'
import { ShopApi, ShopVO } from '@/api/mall/product/shop'
import { Sku } from '@/api/mall/product/spu'
import { number } from 'vue-types'
/** 商品库存 表单 */
defineOptions({ name: 'ShopStockForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const skuRef = ref({
  shopStockList: [
    {
      shopId: undefined,
      shopName: undefined,
      shopType: undefined,
      stock: 0
    }
  ]
})
const formRules = reactive({
  shopId: [{ required: true, message: '店铺不能为空', trigger: 'blur' }],
  stock: [{ required: true, message: '当前库存数量不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const selectedShopId = ref(null)

const shopList = ref()

const queryParams2 = reactive({
  pageNo: 1,
  pageSize: 100
})

/** 查询列表 */
const getShopList = async () => {
  try {
    const data = await ShopApi.getShopPage(queryParams2)
    shopList.value = data.list
  } finally {
  }
}

let queryParams = reactive({
  pageNo: 1,
  pageSize: 100,
  skuId: 0
})

/** 打开弹窗 */
const open = async (sku: Sku) => {
  debugger
  dialogVisible.value = true
  resetForm()
  getShopList()
  // 修改时，设置数据
  formLoading.value = true
  try {
    skuRef.value = sku
    queryParams.skuId = sku.id
    const data = await ProductInventoryApi.getProductInventoryPage(queryParams)
    skuRef.value.shopStockList = data.list
  } finally {
    formLoading.value = false
  }
}

const handleDelete = (shopId) => {
  skuRef.value.shopStockList = skuRef.value.shopStockList.filter((item) => item.shopId !== shopId)
}
const batchSetStock = () => {
  const existingShopIds = skuRef.value.shopStockList.map((item) => item.shopId)
  const newShops = shopList.value.filter((item) => !existingShopIds.includes(item.id))

  newShops.forEach((shop) => {
    skuRef.value.shopStockList.push({
      shopId: shop.id,
      shopName: shop.name,
      shopType: shop.type,
      stock: 0
    })
  })
}

const setStock = () => {
  if (!selectedShopId.value) {
    // 未选择店铺
    message.alert('请先选择一个店铺')
    return
  }

  // 检查店铺是否已存在
  const isShopExists = skuRef.value.shopStockList.some(
    (item) => item.shopId === selectedShopId.value
  )
  if (isShopExists) {
    message.alert('该店铺已存在')
    return
  }

  // 找到选中的店铺信息
  const selectedShop = shopList.value.find((item) => item.id === selectedShopId.value)
  if (selectedShop) {
    // 添加到 shopStockList 中
    skuRef.value.shopStockList.push({
      shopId: selectedShop.id,
      shopName: selectedShop.name,
      shopType: selectedShop.type,
      stock: 0
    })
  }

  // 清空选择
  selectedShopId.value = null
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  // 提交请求
  formLoading.value = true
  try {
    dialogVisible.value = false
    console.log(skuRef.value.shopStockList)
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {}
</script>
<style scoped>
.shop-selector {
  margin-bottom: 10px !important;
  padding-bottom: 10px !important;
  margin-bottom: 20px; /* 底部间距 */
}
</style>
